import { getInstance } from "../node_modules/utils-lib-js/dist/esm/index.js";
// 兼容处理
const __SpeechRecognition = webkitSpeechRecognition ?? SpeechRecognition;
const __SpeechSynthesis = speechSynthesis ?? webkitSpeechSynthesis;

export class SpeechRec extends __SpeechRecognition {
  constructor(opts, ...params) {
    super(opts, ...params);
    this.defineProps(this, opts, ["continuous", "interimResults"]);
    return this;
  }
  // 识别成功的钩子函数
  result(fn) {
    this.addEventListener("result", fn);
  }
  // 识别结束的钩子函数
  end(fn) {
    this.addEventListener("end", fn);
  }
  // 重置识别状态
  reset() {
    this.stop();
    this.start();
  }
  // 浅复制对象属性
  defineProps(source, target, keys = []) {
    keys.forEach((it) => {
      source[it] = target[it];
    });
  }
}
export class SpeechSyn {
  // 语音合成操作
  speak(str) {
    const speakText = new SpeechSynthesisUtterance(str);
    __SpeechSynthesis.speak(speakText);
  }
}
// 类的单例
export const speechRec = (...p) => getInstance(SpeechRec, false, ...p);
export const speechSyn = getInstance(SpeechSyn, false);
